package top.withwings.bonus.bonus.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.withwings.bonus.bonus.pojo.BonusForm;
import top.withwings.bonus.bonus.pojo.Good;
import top.withwings.bonus.bonus.pojo.Rate;
import top.withwings.bonus.bonus.repo.BonusFormRepo;
import top.withwings.bonus.common.pojo.PageParam;
import top.withwings.bonus.common.pojo.PagedData;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class BonusFormService {

    @Autowired
    private BonusFormRepo bonusFormRepo;



    public int create(BonusForm bonusForm) {
        calculateAmount(bonusForm);
        resetComputation(bonusForm);
        return bonusFormRepo.create(bonusForm);
    }


    public void delete(int bonusFormId) {

        BonusForm bonusForm = bonusFormRepo.findById(bonusFormId);
        if (bonusForm == null) {
            throw new IllegalArgumentException("非法的ID");
        }
        bonusFormRepo.delete(bonusFormId);
    }

    public void update(BonusForm bonusForm) {
        calculateAmount(bonusForm);
        resetComputation(bonusForm);
        bonusFormRepo.update(bonusForm);
    }


    public BonusForm findById(int bonusFormId) {
        return bonusFormRepo.findById(bonusFormId);
    }

    public List<BonusForm> search(PageParam pageParam, Integer salesmanId, Date startTime, Date endTime) {

        return bonusFormRepo.search(pageParam, salesmanId, startTime, endTime);
    }

    public int count(Integer salesmanId, Date startTime, Date endTime) {
        return bonusFormRepo.count(salesmanId, startTime, endTime);
    }


    @Transactional(readOnly =true)
    public PagedData<BonusForm> getBonusFormPage(PageParam pageParam, Integer salesmanId, Date startTime, Date endTime){

        int count = this.count(salesmanId, startTime, endTime);
        if(count == 0 ){
            return PagedData.emptyPage();
        }else{
            List<BonusForm> BonusForms = this.search(pageParam, salesmanId, startTime, endTime);
            return PagedData.create(BonusForms,count);
        }

    }


    private void calculateAmount(BonusForm bonusForm) {
        BigDecimal bg = new BigDecimal(bonusForm.getPrice() * bonusForm.getQuantity());
        bonusForm.setAmount( bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
    }


    private void resetComputation(BonusForm bonusForm) {
        bonusForm.setFinalRate(Rate.REQUIRE_COMPUTATION);
        bonusForm.setSingleRates(Arrays.asList(Rate.REQUIRE_COMPUTATION, Rate.REQUIRE_COMPUTATION, Rate.REQUIRE_COMPUTATION));
        bonusForm.setComputedDate(null);
    }

}